package data;

import database.DataBaseConnection;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utility.Utility;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;

public class RankRecordData {
    private int pageNumber;
    private int pageSize;
    private String order;
    private String column;
    private String table;

    public RankRecordData(int pageNumber, int pageSize, String order, String column, String table) {
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        this.order = order;
        this.column = column;
        this.table = table;
    }

    public String rank() {
        String count = "SELECT count(DISTINCT " + column + ") as number from " + table;
        String query = "SELECT " + column + " as column_name,count(*) as count FROM " + table + " GROUP BY "
                + column + " order by count " + this.order + " limit " + this.pageNumber + "," + this.pageSize;
        Connection connection = DataBaseConnection.getConnection();
        if (connection != null) {
            ResultSet countResult = DataBaseConnection.query(connection, count);
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            int totalNumber = 0;
            try {
                while (countResult != null && countResult.next()) {
                    totalNumber = countResult.getInt("number");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            ResultSet queryResult = DataBaseConnection.query(connection, query);
            HashMap<String, Integer> hashMap = new HashMap<>();
            try {
                while (queryResult != null && queryResult.next()) {
                    String key = queryResult.getString("column_name");
                    int val = queryResult.getInt("count");
                    hashMap.put(key, val);
                }
                jsonArray = Utility.sortHashMapByValues(hashMap, column);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            jsonObject.put("total", totalNumber);
            jsonObject.put("rows", jsonArray);
            DataBaseConnection.closeConnection(connection);
            return jsonObject.toString();
        } else {
            return "";
        }
    }
}
